/**
 * Memento.java
 * 19/05/2011 14:17:38
 */
package model.memento;

import javax.swing.event.ChangeListener;
import javax.swing.event.UndoableEditEvent;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;

import model.StateSupport;
import resources.GlobalSettings;

/**
 * @author walber
 * 
 */
public class MementoManager extends UndoManager {

	private static final long serialVersionUID = 9154470824743000024L;

	/**
	 * Lista de listeners del evento undoableEditHappened
	 */
	private StateSupport undoableEditHappenedEventListeners;

	public MementoManager() {
		super();
		this.setLimit(GlobalSettings.limitUndoRedo);
		this.undoableEditHappenedEventListeners = new StateSupport();
	}

	/**
	 * Agregar un edit al undomanager
	 */
	@Override
	public void undoableEditHappened(UndoableEditEvent evt) {
		super.addEdit(evt.getEdit());
		// lanzar evento para refrescar botones
		undoableEditHappenedEventListeners.fireStateChangedEvent();
	}

	/**
	 * @see javax.swing.undo.UndoManager#redo()
	 */
	@Override
	public synchronized void redo() throws CannotRedoException {
		super.redo();
		// lanzar evento para refrescar botones
		undoableEditHappenedEventListeners.fireStateChangedEvent();
	}
	
	/**
	 * @see javax.swing.undo.UndoManager#undo()
	 */
	@Override
	public synchronized void undo() throws CannotUndoException {
		super.undo();
		// lanzar evento para refrescar botones
		undoableEditHappenedEventListeners.fireStateChangedEvent();
	}
	
	/**
	 * @see javax.swing.undo.UndoManager#discardAllEdits()
	 */
	@Override
	public synchronized void discardAllEdits() {
		super.discardAllEdits();
		// lanzar evento para refrescar botones
		undoableEditHappenedEventListeners.fireStateChangedEvent();
	}
	
	/**
	 * Agregar un listener a la lista.
	 * 
	 * @param listener
	 */
	public void addUndoableEditHappenedEventListener(ChangeListener listener) {
		undoableEditHappenedEventListeners.addStateChangeListener(listener);
	}

	/**
	 * Borrar un listener de la lista.
	 * 
	 * @param listener
	 */
	public void removeUndoableEditHappenedEventListener(ChangeListener listener) {
		undoableEditHappenedEventListeners.removeStateChangeListener(listener);
	}
}
